<template>
  <div class="coupon-content">
    <el-tabs v-model="localStatus" @tab-change="handleStatusChange">
      <el-tab-pane label="未使用" name="1"></el-tab-pane>
      <el-tab-pane label="已使用" name="2"></el-tab-pane>
      <el-tab-pane label="已过期" name="3"></el-tab-pane>
    </el-tabs>
    
    <div class="coupon-list" v-loading="loading">
      <div class="coupon-grid">
        <div 
          class="coupon-card" 
          v-for="coupon in coupons" 
          :key="coupon.id"
          @click="showCouponDetail(coupon)"
        >
          <div class="coupon-main">
            <div class="coupon-amount">
              <template v-if="coupon.discountType === 1 || coupon.discountType === 4">
                <span class="amount-value">¥{{ coupon.discountValue / 100 }}</span>
                <span class="amount-condition">满{{ coupon.thresholdAmount / 100 }}可用</span>
              </template>
              <template v-else-if="coupon.discountType === 2">
                <span class="amount-value">{{ coupon.discountValue / 10 }}折</span>
              </template>
              <template v-else-if="coupon.discountType === 3">
                <span class="amount-value">¥{{ coupon.discountValue / 100 }}</span>
                <span class="amount-label">无门槛</span>
              </template>
            </div>
            
            <div class="coupon-info">
              <div class="coupon-name">{{ coupon.name }}</div>
              <div class="coupon-time">有效期至 {{ formatDate(coupon.termEndTime) }}</div>
              <div class="coupon-type">{{ coupon.specific ? '指定商品' : '全场通用' }}</div>
            </div>
          </div>
          
          <div class="coupon-status">
            <el-tag 
              :type="localStatus === '1' ? 'primary' : localStatus === '2' ? 'success' : 'info'"
              size="small"
            >
              {{ localStatus === '1' ? '未使用' : localStatus === '2' ? '已使用' : '已过期' }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 优惠券详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="优惠券详情"
      width="500px"
      class="coupon-detail-dialog"
    >
      <div class="coupon-detail" v-if="selectedCoupon">
        <div class="detail-header">
          <div class="detail-amount">
            <template v-if="selectedCoupon.discountType === 1 || selectedCoupon.discountType === 4">
              <span class="detail-value">¥{{ selectedCoupon.discountValue / 100 }}</span>
              <span class="detail-condition">满{{ selectedCoupon.thresholdAmount / 100 }}可用</span>
            </template>
            <template v-else-if="selectedCoupon.discountType === 2">
              <span class="detail-value">{{ selectedCoupon.discountValue / 10 }}折</span>
            </template>
            <template v-else-if="selectedCoupon.discountType === 3">
              <span class="detail-value">¥{{ selectedCoupon.discountValue / 100 }}</span>
              <span class="detail-label">无门槛</span>
            </template>
          </div>
        </div>
        
        <div class="detail-body">
          <el-descriptions :column="1" size="small" border>
            <el-descriptions-item label="优惠券名称">{{ selectedCoupon.name }}</el-descriptions-item>
            <el-descriptions-item label="优惠类型">
              <span v-if="selectedCoupon.discountType === 1">每满减</span>
              <span v-else-if="selectedCoupon.discountType === 2">折扣</span>
              <span v-else-if="selectedCoupon.discountType === 3">无门槛</span>
              <span v-else-if="selectedCoupon.discountType === 4">满减</span>
            </el-descriptions-item>
            <el-descriptions-item label="适用范围">
              {{ selectedCoupon.specific ? '指定商品' : '全场通用' }}
            </el-descriptions-item>
            <el-descriptions-item label="有效期限">
              {{ formatDate(selectedCoupon.termEndTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag 
                :type="localStatus === '1' ? 'primary' : localStatus === '2' ? 'success' : 'info'"
                size="small"
              >
                {{ localStatus === '1' ? '未使用' : localStatus === '2' ? '已使用' : '已过期' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            v-if="localStatus === '1'"
            @click="useCoupon()"
          >
            去使用
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import promotionApi from '@/api/promotion'
import { CouponVO } from '@/type/coupon'

const props = defineProps<{
  status: string
}>()

const router = useRouter()
const localStatus = ref(props.status)
const coupons = ref<CouponVO[]>([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const selectedCoupon = ref<CouponVO | null>(null)

const handleStatusChange = (status: string) => {
  localStatus.value = status
  currentPage.value = 1
  fetchCoupons()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCoupons()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchCoupons()
}

// 获取优惠券列表
const fetchCoupons = async () => {
  loading.value = true
  try {
    const response = await promotionApi.getMyCouponsPage(
      currentPage.value,
      pageSize.value,
      parseInt(localStatus.value),
      false,
      'termEndTime'
    )
    
    coupons.value = response.data.data.list || []
    total.value = response.data.data.total || 0
  } catch (error:any) {
    ElMessage.error('获取优惠券失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 使用优惠券
const useCoupon = () => {
    dialogVisible.value = false
    // 跳转到购物车页面
    router.push({ name: 'shoppingcart' })
}

// 显示优惠券详情
const showCouponDetail = (coupon: CouponVO) => {
  selectedCoupon.value = coupon
  dialogVisible.value = true
}

// 时间格式化方法
const formatDate = (dateStr: string | null): string => {
  if (!dateStr) return '未知'

  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

// 监听状态变化
watch(() => props.status, (newStatus) => {
  if (newStatus !== localStatus.value) {
    localStatus.value = newStatus
    currentPage.value = 1
    fetchCoupons()
  }
})

onMounted(() => {
  localStatus.value = props.status
  // 组件挂载时获取一次数据
  fetchCoupons()
})
</script>

<style scoped>
.coupon-content {
  max-width: 1200px;
  margin: 0 auto;
}

.coupon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.coupon-card {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.coupon-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.coupon-main {
  display: flex;
  padding: 20px;
}

.coupon-amount {
  width: 120px;
  text-align: center;
  padding-right: 15px;
  border-right: 1px dashed #e6e6e6;
}

.amount-value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
  margin-bottom: 5px;
}

.amount-condition,
.amount-label {
  font-size: 12px;
  color: #666;
}

.coupon-info {
  flex: 1;
  padding-left: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.coupon-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #333;
}

.coupon-time,
.coupon-type {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.coupon-status {
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}

.coupon-detail-dialog :deep(.el-dialog__body) {
  padding: 10px 20px 20px;
}

.detail-header {
  background: linear-gradient(90deg, #ff6b6b, #ff8e53);
  border-radius: 8px;
  padding: 30px 20px;
  margin-bottom: 20px;
  text-align: center;
  color: white;
}

.detail-amount {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.detail-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
}

.detail-condition,
.detail-label {
  font-size: 14px;
  opacity: 0.9;
}

.detail-body {
  padding: 0 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 0 20px 20px;
}
</style>